import { ref } from 'vue'
import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import router, { constantRoutes, asyncRoutes as dynamicRoutes } from '@/router'
import Layout from '@/layout/index.vue'
import ParentView from '@/components/ParentView/index.vue'
import { myMenu } from '@/apis'
import Has from '@/utils/has'

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../../views/**/*.vue')
const rrrr = [
  {
    id: 174,
    parent_id: 0,
    icon: null,
    uri: '/',
    is_link: 0,
    permission_list: [],
    extend:
      '{"title":"首页","path":"/","redirect":"/ms","component":"Layout","svgIcon":"menu-home","hidden":false,"affix":false,"keepAlive":true,"bold":true}',
    name: 'ms',
    guard_name: 'admin',
    sequence: 2000,
    created_at: '2024-03-11 14:36:06',
    updated_at: '2024-03-11 14:41:13',
    children: [
      {
        id: 175,
        parent_id: 174,
        icon: null,
        uri: 'ms',
        is_link: 0,
        permission_list: [],
        extend:
          '{"title":"首页","path":"ms","component":"ms/index","hidden":false,"affix":false,"keepAlive":true,"bold":true}',
        name: 'ms',
        guard_name: 'admin',
        sequence: 1,
        created_at: '2024-03-11 14:36:40',
        updated_at: '2024-03-11 14:41:01'
      }
    ]
  },
  {
    id: 102,
    parent_id: 0,
    icon: null,
    uri: '/system',
    is_link: 0,
    permission_list: [
      'api.v1.config.appVersionConfig.list',
      'api.v1.config.appVersionConfig.update',
      'api.v1.config.adminConfig.update',
      'api.v1.config.adminConfig.list',
      'api.v1.config.appVersionConfig.import'
    ],
    extend:
      '{"title":"系统管理","path":"/system","redirect":"/system/app","component":"Layout","svgIcon":"menu-system","hidden":false,"affix":false,"keepAlive":true,"bold":true}',
    name: 'system',
    guard_name: 'admin',
    sequence: 950,
    created_at: '2023-09-15 14:26:15',
    updated_at: '2024-03-11 15:01:14',
    children: [
      {
        id: 103,
        parent_id: 102,
        icon: 'icon-menu',
        uri: 'app',
        is_link: 0,
        permission_list: [],
        extend:
          '{"title":"APP设置","path":"app","component":"system/app/index","hidden":false,"affix":false,"keepAlive":true}',
        name: 'app',
        guard_name: 'admin',
        sequence: 1000,
        created_at: '2023-09-15 14:26:49',
        updated_at: '2023-09-15 17:25:50'
      },
      {
        id: 198,
        parent_id: 102,
        icon: null,
        uri: 'domain',
        is_link: 0,
        permission_list: [],
        extend:
          '{"title":"域名管理","path":"domain","component":"system/domain/index","hidden":false,"affix":false,"keepAlive":true,"bold":false}',
        name: 'domain',
        guard_name: 'admin',
        sequence: 998,
        created_at: '2024-11-04 15:19:26',
        updated_at: '2024-11-04 15:20:11'
      },
      {
        id: 104,
        parent_id: 102,
        icon: 'icon-menu',
        uri: 'weChatPush',
        is_link: 0,
        permission_list: [],
        extend:
          '{"title":"微信推送","path":"weChatPush","component":"system/weChatPush/index","hidden":false,"affix":false,"keepAlive":true}',
        name: 'weChatPush',
        guard_name: 'admin',
        sequence: 990,
        created_at: '2023-09-15 14:27:23',
        updated_at: '2023-09-15 17:25:57'
      },
      {
        id: 105,
        parent_id: 102,
        icon: 'icon-menu',
        uri: 'manager',
        is_link: 0,
        permission_list: [
          'admin-user.index',
          'admin-user.show',
          'admin-user.store',
          'admin-user.update',
          'admin-user.destroy',
          'admin-user.roles',
          'admin-user.assign-roles'
        ],
        extend:
          '{"title":"后台用户","path":"manager","component":"system/manager/index","hidden":false,"affix":false,"keepAlive":true}',
        name: 'manager',
        guard_name: 'admin',
        sequence: 980,
        created_at: '2023-09-15 14:28:03',
        updated_at: '2023-09-16 15:19:54'
      },
      {
        id: 106,
        parent_id: 102,
        icon: 'icon-menu',
        uri: 'role',
        is_link: 0,
        permission_list: [
          'role.index',
          'role.show',
          'role.store',
          'role.update',
          'role.destroy',
          'role.permissions',
          'role.assign-permissions',
          'role.guard-name-roles'
        ],
        extend:
          '{"title":"角色管理","path":"role","component":"system/role/index","hidden":false,"affix":false,"keepAlive":true,"bold":false}',
        name: 'role',
        guard_name: 'admin',
        sequence: 970,
        created_at: '2023-09-15 14:28:35',
        updated_at: '2023-10-13 10:51:24'
      },
      {
        id: 109,
        parent_id: 102,
        icon: null,
        uri: 'pAssignment',
        is_link: 0,
        permission_list: [
          'role.index',
          'role.show',
          'role.store',
          'role.update',
          'role.destroy',
          'role.permissions',
          'role.assign-permissions',
          'role.guard-name-roles'
        ],
        extend:
          '{"title":"角色权限分配","path":"pAssignment","component":"system/role/PAssignment","activeMenu":"system/role","hidden":true,"affix":false,"keepAlive":true}',
        name: 'pAssignment',
        guard_name: 'admin',
        sequence: 969,
        created_at: '2023-09-16 09:24:34',
        updated_at: '2023-09-16 15:19:30'
      },
      {
        id: 107,
        parent_id: 102,
        icon: 'icon-menu',
        uri: 'dept',
        is_link: 0,
        permission_list: [
          'permission.index',
          'permission.show',
          'permission.store',
          'permission.update',
          'permission.destroy'
        ],
        extend:
          '{"title":"权限管理","path":"dept","component":"system/dept/index","hidden":false,"affix":false,"keepAlive":true}',
        name: 'dept',
        guard_name: 'admin',
        sequence: 960,
        created_at: '2023-09-15 14:29:22',
        updated_at: '2023-09-16 15:19:07'
      },
      {
        id: 108,
        parent_id: 102,
        icon: 'icon-menu',
        uri: 'menus',
        is_link: 0,
        permission_list: ['menu.index', 'menu.show', 'menu.store', 'menu.update', 'menu.destroy'],
        extend:
          '{"title":"菜单管理","path":"menus","component":"system/menu/index","hidden":false,"affix":false,"keepAlive":true}',
        name: 'menus',
        guard_name: 'admin',
        sequence: 950,
        created_at: '2023-09-15 14:29:51',
        updated_at: '2023-09-16 15:14:35'
      },
      {
        id: 110,
        parent_id: 102,
        icon: 'icon-menu',
        uri: 'loginLog',
        is_link: 0,
        permission_list: [
          'admin-user.index',
          'admin-user.show',
          'admin-user.store',
          'admin-user.update',
          'admin-user.destroy',
          'admin-user.roles',
          'admin-user.assign-roles',
          'log.login.list',
          'log.operation.list'
        ],
        extend:
          '{"title":"登录日志","path":"loginLog","component":"system/loginLog/index","hidden":false,"affix":false,"keepAlive":true}',
        name: 'loginLog',
        guard_name: 'admin',
        sequence: 940,
        created_at: '2023-09-18 10:28:12',
        updated_at: '2023-09-18 16:58:08'
      },
      {
        id: 112,
        parent_id: 102,
        icon: 'icon-menu',
        uri: 'operationLog',
        is_link: 0,
        permission_list: [
          'admin-user.index',
          'admin-user.show',
          'admin-user.store',
          'admin-user.update',
          'admin-user.destroy',
          'admin-user.roles',
          'admin-user.assign-roles',
          'log.login.list',
          'log.operation.list'
        ],
        extend:
          '{"title":"操作日志","path":"operationLog","component":"system/operationLog/index","hidden":false,"affix":false,"keepAlive":true}',
        name: 'operationLog',
        guard_name: 'admin',
        sequence: 930,
        created_at: '2023-09-18 12:11:52',
        updated_at: '2023-09-18 16:58:20'
      },
      {
        id: 111,
        parent_id: 102,
        icon: 'icon-menu',
        uri: 'homeSetting',
        is_link: 0,
        permission_list: [
          'admin-user.index',
          'admin-user.show',
          'admin-user.store',
          'admin-user.update',
          'admin-user.destroy',
          'admin-user.roles',
          'admin-user.assign-roles',
          'log.login.list',
          'log.operation.list'
        ],
        extend:
          '{"title":"应用菜单管理","path":"homeSetting","component":"system/homeSetting/index","hidden":false,"affix":false,"keepAlive":true}',
        name: 'homeSetting',
        guard_name: 'admin',
        sequence: 920,
        created_at: '2023-09-18 11:18:22',
        updated_at: '2023-09-18 16:58:23'
      },
      {
        id: 115,
        parent_id: 102,
        icon: null,
        uri: 'homeSettingEdit',
        is_link: 0,
        permission_list: [],
        extend:
          '{"title":"应用编辑","path":"homeSettingEdit","component":"system/homeSetting/Edit","activeMenu":"system/homeSetting/index","hidden":true,"affix":false,"keepAlive":true}',
        name: 'homeSettingEdit',
        guard_name: 'admin',
        sequence: 910,
        created_at: '2023-09-19 09:45:42',
        updated_at: '2023-09-19 09:45:52'
      }
    ]
  }
]

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRoutes: RouteRecordRaw[], lastRouter: boolean | RouteRecordRaw = false, type = false) {
  return asyncRoutes.filter((route) => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component && typeof route.component === 'string') {
      // Layout ParentView 组件特殊处理
      if (route['component'] === 'Layout') {
        route['component'] = Layout as never
      } else if (route['component'] === 'ParentView') {
        route['component'] = ParentView as never
      } else {
        route['component'] = loadView(route['component']) as never
      }
    }
    if (route.children !== null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenRoutes: RouteRecordRaw[], lastRouter: boolean | RouteRecordRaw = false) {
  let children: RouteRecordRaw[] = []
  childrenRoutes.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (typeof el.component === 'string' && el['component'] === 'ParentView' && !lastRouter) {
        ;(el['children'] as RouteRecordRaw[]).forEach((c: RouteRecordRaw) => {
          c.path = el['path'] + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter && typeof lastRouter === 'object') {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes: RouteRecordRaw[]) {
  const arr: RouteRecordRaw[] = []
  routes.forEach((route) => {
    if (route.meta?.permissions) {
      if (Has.hasPermOr(route.meta?.permissions)) {
        arr.push(route)
      }
    } else if (route.meta?.roles) {
      if (Has.hasRoleOr(route.meta?.roles)) {
        arr.push(route)
      }
    }
  })
  return arr
}

// 加载模块
export const loadView = (view: string) => {
  let res
  for (const path in modules) {
    const dir = path.split('views/')[1].split('.vue')[0]
    if (dir === view) {
      res = () => modules[path]()
    }
  }
  return res
}

const storeSetup = () => {
  const routes = ref<RouteRecordRaw[]>([]) // 常驻路由 + 动态路由（这时候component已经从字符串转为模块）
  const topbarRoutes = ref<RouteRecordRaw[]>([]) // 页签路由
  const sidebarRoutes = ref<RouteRecordRaw[]>([]) // 侧边栏路由

  const setRoutes = (routesArray: RouteRecordRaw[]) => {
    routes.value = constantRoutes.concat(routesArray)
  }

  const setTopbarRoutes = (routes: RouteRecordRaw[]) => {
    topbarRoutes.value = routes
  }

  const setSidebarRoutes = (routes: RouteRecordRaw[]) => {
    sidebarRoutes.value = routes
  }

  // 路由格式化
  const formatRouter = (arr: any) => {
    return arr.map((item: any) => {
      if (typeof item.extend === 'string') {
        item.extend = JSON.parse(item.extend)
      }
      return {
        path: item.extend.path,
        name: item.name,
        redirect: item.extend.redirect,
        component: item.extend.component,
        children: item.children && item.children.length ? formatRouter(item.children) : undefined,
        meta: {
          hidden: item.extend.hidden,
          title: item.extend.title,
          svgIcon: item.extend.svgIcon,
          icon: item.icon || item.extend.icon,
          keepAlive: item.extend.keepAlive,
          affix: item.extend.affix,
          activeMenu: item.extend.activeMenu,
          bold: item.extend.bold
        }
      }
    })
  }
  /** 生成路由 */
  const generateRoutes = (): Promise<RouteRecordRaw[]> => {
    return new Promise((resolve) => {
      // 向后端请求路由数据
      myMenu().then((res) => {
        const routers = formatRouter(res.data)
        // const routers = formatRouter(rrrr)
        const sdata = JSON.parse(JSON.stringify(routers))
        const rdata = JSON.parse(JSON.stringify(routers))
        const defaultData = JSON.parse(JSON.stringify(routers))
        const sidebarRoutes = filterAsyncRouter(sdata)
        const rewriteRoutes = filterAsyncRouter(rdata, false, true)
        const defaultRoutes = filterAsyncRouter(defaultData)
        const asyncRoutes = filterDynamicRoutes(dynamicRoutes)
        asyncRoutes.forEach((route) => {
          router.addRoute(route)
        })
        // console.log(rewriteRoutes)
        setRoutes(rewriteRoutes)
        setSidebarRoutes(constantRoutes.concat(sidebarRoutes))
        setTopbarRoutes(defaultRoutes)
        resolve(rewriteRoutes)
      })
    })
  }

  return {
    routes,
    topbarRoutes,
    sidebarRoutes,
    generateRoutes
  }
}

export const usePermissionStore = defineStore('permission', storeSetup, { persist: true })
